import Taro from '@tarojs/taro'
import { action, observable, computed } from 'mobx'

// apis
import * as productsInfoApi from '../../apis/productsInfoApi'

// models
import Advertisement from '../../models/Advertisement'
import ProductsInfo from '../../models/ProductsInfo'

// store
import payStore from '../pay/store'

class ProductDetailStore {
  @observable
  product?: ProductsInfo

  @observable
  buyQuantity: number = 1 // 购买数量

  @action
  navigateTo({ productId }: { productId: number }): any {
    Taro.navigateTo({
      url: `/pages/productDetail/index?productId=${productId}`,
    })
  }

  /**
   * 总计
   */
  @computed.struct
  get totalPrice() {
    const price = this.product ? this.product.shoppPrice : 0
    return this.buyQuantity * price
  }

  @action
  async init(params: { productId: number }) {
    Taro.showLoading({ title: '加载中...' })
    // 加载商品
    await this.loadProducts(params.productId)

    Taro.hideLoading()
  }

  /**
   * 加载商品
   */
  @action
  async loadProducts(id: number) {
    const resp = await productsInfoApi.getById({ id })

    this.product = resp.data
  }

  @action
  changeQuantity = (value: number) => {
    if (value < 0) return
    this.buyQuantity = value
  }
  @action
  comfirm = () => {
    if (this.buyQuantity <= 0) return

    payStore.product = this.product
    payStore.productCount = this.buyQuantity

    Taro.navigateTo({
      url: '/pages/pay/index',
    })
  }
}

export default new ProductDetailStore()
